/*
 * Copyright 2009 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.configleon.resource;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.util.WebUtils;

public class WebPropertyResources extends AbstractPropertyResources implements ServletContextAware {

    private Log logger = LogFactory.getLog(WebPropertyResources.class);

    private ServletContext servletContext;

    private String resourcePath;

    @Override
    public List<Resource> getResources(String configLocation)
        throws FileNotFoundException {
        String context = getContext();

        if (resourcePath == null) {
            resourcePath = "WEB-INF/config/";
        }

        List<Resource> resources = new ArrayList<Resource>();
        addResource(resources, resourcePath + "config-global.properties");
        addResource(resources, resourcePath + configLocation + "/config-" + configLocation + "-global.properties");
        addResource(resources, resourcePath + configLocation + "/config-" + configLocation + "-" + context + ".properties");

        resources.addAll(super.getResources(configLocation));

        return resources;
    }

    protected String getContext()
            throws FileNotFoundException {
        String realPath = StringUtils.cleanPath(WebUtils.getRealPath(servletContext, "/"));
        if (logger.isInfoEnabled()) {
            logger.info("The real path is " + realPath);
        }
        String[] paths = StringUtils.tokenizeToStringArray(realPath, "/", true, true);

        String context = paths[paths.length - 1];
        if (logger.isInfoEnabled()) {
            logger.info("The context is " + context);
        }

        return context;
    }

    protected ServletContext getServletContext() {
        return servletContext;
    }
    
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    protected String getResourcePath() {
        return resourcePath;
    }

    public void setResourcePath(String resourcePath) {
        this.resourcePath = resourcePath;
    }
}
